<template>
  <div class="fix-btn">
    <i class="fix-btn-svg"></i>
    <transition name="fade">
      <i class="fix-btn-top" @click="backTop" v-show="isShow"></i>
    </transition>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isShow: false
    };
  },
  mounted() {
    window.addEventListener("scroll", this.scrollToTop);
  },
  destroyed() {
    window.removeEventListener("scroll", this.scrollToTop);
  },

  methods: {
    // 点击图片回到顶部方法，加计时器是为了过渡顺滑
    backTop() {
      const that = this;
      let timer = setInterval(() => {
        let ispeed = Math.floor(-that.scrollTop / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          that.scrollTop + ispeed;
        if (that.scrollTop === 0) {
          clearInterval(timer);
        }
      }, 16);
    },

    // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
    scrollToTop() {
      const that = this;
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      that.scrollTop = scrollTop;
      if (that.scrollTop > 80) {
        that.isShow = true;
      } else {
        that.isShow = false;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.fix-btn {
  &-svg {
    width: 36px;
    height: 36px;
    background: url("../assets/img/btn-svc.png") no-repeat;
    background-size: cover;
    display: block;
    position: fixed;
    z-index: 200;
    bottom: 80px;
    left: 10px;
  }
  &-top {
    width: 36px;
    height: 36px;
    background: url("../assets/img/top.png") no-repeat;
    background-size: cover;
    display: block;
    position: fixed;
    z-index: 200;
    bottom: 80px;
    right: 10px;
  }
  .fade-enter-active,
  .fade-leave-active {
    transition: all 0.3s;
  }
  .fade-enter,
  .fade-leave-to {
    opacity: 0;
  }
}
</style>